require('module-alias/register');
// 使用dotenv全局配置
require('dotenv').config()
const express = require("express");
const bodyParser = require('body-parser');
const fs = require("fs");
const path = require("path");
const cors = require('cors');
require('express-async-errors');
// 导入数据库连接模块
const sequelize = require("./db/index");
// 数据库生成模式 force:true 强制创建 alter:true 合并创建
const MYSQL_GENERATE_MODE = process.env.MYSQL_GENERATE_MODE
sequelize.sync({[MYSQL_GENERATE_MODE]: true});

const UPLOAD_FOLDER = path.join(__dirname, "uploads");

// 确保目录存在
fs.mkdirSync(UPLOAD_FOLDER, { recursive: true });

const app = express();
const PORT = 9000;
app.use(cors());
const router = express.Router();
// 解析post请求的body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const options = {
  // 设置静态资源可跨域访问
  setHeaders: function(res, path, stat) {
    res.set("Access-Control-Allow-Origin", "*");
  }
}

// 静态文件服务
app.use("/upload/", express.static(UPLOAD_FOLDER, options));

// 引入路由
require('./routes')(router, app);

app.listen(PORT, () => {
  console.log(`Node server running at http://localhost:${PORT}`);
});
